#!/bin/bash 

# Runs the bonnie++ test on filesystems...

# Copyright (C) 2003-2006 IBM
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

TEST_PID=$$

# Try to find bonnie++ on the system
BONNIE=`which bonnie++ 2> /dev/null`

if [ -z "$BONNIE" ]; then
	BONNIE=`ls $POUNDER_OPTDIR/bonnie++*/bonnie++`
	if [ -z "$BONNIE" ]; then
		echo "Cannot find bonnie++; did you run Install?"
		exit -1
	fi
fi

# Note old errors
LOGFILE=/proc/$$/fd/1
OLD_ERRORS=`egrep -ic "(err|fail|invalid|cannot|denied)" $LOGFILE`

# How much RAM do we have?
RAM=`cat /proc/meminfo | grep MemTotal | awk -F " " '{print $2}'`
SPACE_REQUIRED=`expr $RAM \* 4`

# Now figure out where we have mounted filesystems
MOUNTS=`egrep "(ext|reiser)" /proc/mounts | awk -F " " '{print $2}'`

rm -rf $POUNDER_TMPDIR/bonnie-script-$TEST_PID
echo '#/bin/bash' > $POUNDER_TMPDIR/bonnie-script-$TEST_PID
echo >> $POUNDER_TMPDIR/bonnie-script-$TEST_PID

echo $MOUNTS | sed -e 's/ /\n/g' | while read f; do
	# Clean out space for bonnie
	rm -rf "$f/bonnie/"

	# Do we have enough space? (assume 4x RAM is enough)
	FREE_SPACE=`df -k -P "$f" | tail -1 | awk -F " " '{print $4}'`
	if [ "$FREE_SPACE" -lt "$SPACE_REQUIRED" ]; then
		echo "Insufficient space on $f; not running bonnie."
		continue
	fi
	
	# Set up for bonnie
	mkdir -p "$f/bonnie/"

	# Engage!
	echo $BONNIE -u 0 -d \"$f/bonnie/\" \& >> $POUNDER_TMPDIR/bonnie-script-$TEST_PID
done

echo wait >> $POUNDER_TMPDIR/bonnie-script-$TEST_PID

# Are we actually going to start any bonnie's?
if [ `wc -l < $POUNDER_TMPDIR/bonnie-script-$TEST_PID` -lt 4 ]; then
	echo "Not running bonnie at all.  Abort."
	exit -1
fi

bash $POUNDER_TMPDIR/bonnie-script-$TEST_PID
rm -rf $POUNDER_TMPDIR/bonnie-script-$TEST_PID

# Clean ourselves up
echo $MOUNTS | sed -e 's/ /\n/g' | while read f; do
	# Clean out space for bonnie
	rm -rf "$f/bonnie/"
done

# Did we find any new errors?
NEW_ERRORS=`egrep -ic "(err|fail|invalid|cannot|denied)" $LOGFILE`
ERRORS=$(( NEW_ERRORS - OLD_ERRORS ))
if [ $ERRORS -eq 255 ]; then
        ERRORS=254
fi

exit $ERRORS
